package servlet;

import handler.HandlerFactory;
import handler.IHandler;
import handler.ISetParamHandler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class ApplicationServlet  extends HttpServlet {
    private static final long serialVersionUID = 1L;
    static Logger LOGGER = Logger.getLogger(ApplicationServlet.class.getName());
    
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    	doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        
        String param = request.getParameter("operation");
        IHandler handler = HandlerFactory.getHandler(param);
        String result = null;
        
        if (handler instanceof ISetParamHandler) {
        	result = ((ISetParamHandler)handler).setRequest(request);
        	if (result == "OK") {
        		result = handler.process();
        	}
        } else {
        	result = handler.process();
        }
        
        if(result != null) {
        	out.write(result);
        }
        
    }
}
